package thread;

/**
 * 手写一个死锁代码
 * 所谓的死锁就是线程一拥有锁1，线程二拥有锁2，
 * 双方在拥有自身锁的同时尝试获取对方的锁，最终两个线程就会进入无线等待的状态，这就是死锁。
 */
public class demo36 {
    public static void main(String[] args) {
        Object obj1 = new Object();
        Object obj2 = new Object();
        Runner r1 = new Runner(obj1, obj2, 5000);
        Runner r2 = new Runner(obj2, obj1, 5000);
        new Thread(r1, "r1").start();
        new Thread(r2, "r2").start();
    }
}

class Runner implements Runnable {
    private Object o1;
    private Object o2;
    private int sleepTime;

    public Runner(Object o1, Object o2, int sleepTime) {
        this.o1 = o1;
        this.o2 = o2;
        this.sleepTime = sleepTime;
    }

    public void run() {
        System.out.println("当前线程" + Thread.currentThread().getName() + "获得锁");
        synchronized (o1) {
            try {
                //  这里主要是放大效果
                Thread.sleep(sleepTime);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (o2) {
                System.out.println();
            }
        }
    }
}
